import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:travel/model/coin.dart';
import 'package:travel/utils/colors.dart';
import 'package:travel/utils/radian.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';
import 'package:travel/screen/flutter_screenutil.dart';

class MineCoinController extends GetxController with GetTickerProviderStateMixin {
  RxList<String> tabs = RxList(['金币收入', '金币支出']);

  late TabController tabController;

  @override
  void onInit() {
    tabController = TabController(length: tabs.length, vsync: this);
    super.onInit();
  }

  @override
  void onClose() {
    tabController.dispose();
    super.onClose();
  }
}

class MineCoinView extends GetView<MineCoinController> {
  const MineCoinView({super.key});

  @override
  Widget build(BuildContext context) {
    return buildDefaultTabController(context);
  }

  Widget buildDefaultTabController(BuildContext context) {
    return DefaultTabController(
      length: controller.tabs.length,
      child: Scaffold(
        backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF7f7),
        appBar: AppBar(
          backgroundColor: Colors.white,
          automaticallyImplyLeading: true,
          leading: InkWell(
            onTap: () {
              Get.back();
            },
            child: Icon(
              Icons.arrow_back_ios,
              color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
              size: 20.w,
            ),
          ),
          leadingWidth: 40.w,
          title: Center(
            child: Text('我的金币',
                style: StylesUtils.customTextStyle(
                    color: ColorsUtils.color3333, fontSize: 18.sp, fontWeight: FontWeight.bold)),
          ),
          actions: [
            SizedBox(
              width: 40.w,
            )
          ],
        ),
        body: NestedScrollView(
          headerSliverBuilder: (_, innerBoxIsScrolled) {
            return <Widget>[
              SliverPadding(
                padding: EdgeInsets.symmetric(vertical: 10.w),
                sliver: SliverToBoxAdapter(
                  child: Center(
                    child: Container(
                      width: 345,
                      height: 90,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10.w),
                          gradient: LinearGradient(colors: [
                            ColorsUtils.rgba(255, 190, 99, 1),
                            ColorsUtils.rgba(255, 142, 63, 1)
                          ], stops: const [
                            0,
                            1.0
                          ], transform: GradientRotation(RadianUtils.angleToRadian(180)))),
                      padding: EdgeInsets.symmetric(horizontal: 15.w),
                      child: Column(
                        children: [
                          Expanded(
                              flex: 4,
                              child: Container(
                                alignment: Alignment.bottomLeft,
                                child: Text(
                                  '可用金币 (个)',
                                  style: StylesUtils.customTextStyle(),
                                ),
                              )),
                          Expanded(
                              flex: 7,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    NumberFormat('#,###').format(300000),
                                    style: StylesUtils.customTextStyle(fontSize: 28.sp),
                                  ),
                                  Wrap(
                                    alignment: WrapAlignment.end,
                                    crossAxisAlignment: WrapCrossAlignment.center,
                                    spacing: 2,
                                    children: [
                                      ToolsUtils.assetImageSvg('u3088.svg',
                                          width: 13.w, height: 13.h),
                                      Text(' 规则说明',
                                          style: StylesUtils.textStyle(
                                              color: ColorsUtils.rgba(255, 255, 255, 0.8),
                                              fontSize: 12.sp))
                                    ],
                                  ),
                                ],
                              ))
                        ],
                      ),
                    ),
                  ),
                ),
              ),
              SliverPersistentHeader(
                delegate: _MySliverPersistentHeader(
                    child: Container(
                  width: 300,
                  alignment: Alignment.center,
                  child: ToolsUtils.getClientTabBar(controller.tabs, controller.tabController,
                      isScrollable: false, indicatorSize: TabBarIndicatorSize.tab),
                )),
                pinned: true,
              )
            ];
          },
          body: TabBarView(
            controller: controller.tabController,
            children: const [GoldCoinIncome(), GoldCoinExpenditure()],
          ),
        ),
      ),
    );
  }
}

class _MySliverPersistentHeader extends SliverPersistentHeaderDelegate {
  final Widget child;

  _MySliverPersistentHeader({required this.child});

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    Get.log('shrinkOffset = $shrinkOffset');
    return Center(
      child: Container(
        width: getMaxWidth(shrinkOffset),
        height: 50,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            border: Border(
                bottom:
                    BorderSide(color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2))),
            color: Colors.white,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(getCircular(shrinkOffset)),
                topRight: Radius.circular(getCircular(shrinkOffset)))),
        child: child,
      ),
    );
  }

  double getCircular(double shrinkOffset) {
    return (1 - (shrinkOffset / minExtent)).clamp(0.0, 1) * 10;
  }

  double getMaxWidth(double shrinkOffset) {
    double width = Get.width - 345.0;
    double result = 345.0 + (width / minExtent) * shrinkOffset;
    double r = result.clamp(345, Get.width);
    return r;
  }

  @override
  double get maxExtent => minExtent;

  @override
  double get minExtent => 50;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return this != oldDelegate;
  }
}

/// 金币收入
class GoldCoinIncome extends StatefulWidget {
  const GoldCoinIncome({super.key});

  @override
  State<GoldCoinIncome> createState() => _GoldCoinIncomeState();
}

class _GoldCoinIncomeState extends State<GoldCoinIncome> {
  List<GoldCoinModel> pageList = [];

  bool isLoading = false;

  bool hasNext = true;

  int total = 45;

  late ScrollController scrollController;

  @override
  void initState() {
    scrollController = ScrollController()
      ..addListener(() {
        if (isLoading == false &&
            scrollController.position.pixels >= scrollController.position.maxScrollExtent) {
          setState(() {
            isLoading = true;
          });
          loadMoreData();
        }
      });
    initData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      controller: scrollController,
      slivers: [
        SliverList(
          delegate: SliverChildBuilderDelegate((context, index) {
            var row = pageList[index];
            return Center(
              child: Container(
                width: 345,
                height: 70,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                      bottomLeft:
                          index + 1 < pageList.length ? const Radius.circular(10) : Radius.zero,
                      bottomRight:
                          index + 1 < pageList.length ? const Radius.circular(10) : Radius.zero,
                    )),
                child: Row(
                  children: [
                    Expanded(
                        child: Container(
                      padding: EdgeInsets.only(left: 15.w),
                      child: Column(
                        children: [
                          Expanded(
                              child: Align(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              row.name,
                              style: StylesUtils.customTextStyle(
                                  fontSize: 15.sp, color: ColorsUtils.color3333),
                            ),
                          )),
                          Expanded(
                              child: Align(
                            alignment: Alignment.topLeft,
                            child: Text(
                              row.time,
                              style: StylesUtils.customTextStyle(
                                  fontSize: 12.sp, color: ColorsUtils.color9999),
                            ),
                          ))
                        ],
                      ),
                    )),
                    Center(
                      child: Text(
                        '+${row.count}',
                        style: StylesUtils.customTextStyle(
                            fontSize: 16.sp, color: ColorsUtils.colorFf99),
                      ),
                    )
                  ],
                ),
              ),
            );
          }, childCount: pageList.length),
        ),
        if (hasNext == false) noBottom() else if (isLoading == true) renderBottom()
      ],
    );
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  SliverToBoxAdapter noBottom() {
    return SliverToBoxAdapter(
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 15),
        alignment: Alignment.center,
        child: const Text(
          '已经到底',
          style: TextStyle(
            fontSize: 15,
            color: Color(0xFF333333),
          ),
        ),
      ),
    );
  }

  SliverToBoxAdapter renderBottom() {
    if (isLoading == true) {
      return SliverToBoxAdapter(
          child: Container(
        padding: const EdgeInsets.symmetric(vertical: 15),
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '努力加载中...',
              style: TextStyle(
                fontSize: 15,
                color: Color(0xFF333333),
              ),
            ),
            Padding(padding: EdgeInsets.only(left: 10)),
            SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(strokeWidth: 3),
            ),
          ],
        ),
      ));
    }
    return SliverToBoxAdapter(
        child: Container(
      padding: const EdgeInsets.symmetric(vertical: 15),
      alignment: Alignment.center,
      child: const Text(
        '上拉加载更多',
        style: TextStyle(
          fontSize: 15,
          color: Color(0xFF333333),
        ),
      ),
    ));
  }

  void initData() {
    var r = Random.secure();
    for (var i = 0; i < 10; i++) {
      pageList.add(GoldCoinModel(
          count: r.nextInt(357) + r.nextInt(135), name: '发布图文', time: '2023-11-24 18:51'));
    }
  }

  Future<void> loadMoreData() {
    return Future.delayed(const Duration(seconds: 1), () {
      setState(() {
        if (total > pageList.length) {
          hasNext = true;
          isLoading = false;
          initData();
          return;
        }
        hasNext = false;
        isLoading = false;
      });
    });
  }
}

/// 金币支出
class GoldCoinExpenditure extends StatefulWidget {
  const GoldCoinExpenditure({super.key});

  @override
  State<GoldCoinExpenditure> createState() => _GoldCoinExpenditureState();
}

class _GoldCoinExpenditureState extends State<GoldCoinExpenditure> {
  List<GoldCoinModel> pageList = [];

  bool isLoading = false;

  bool hasNext = true;

  int total = 45;

  late ScrollController scrollController;

  @override
  void initState() {
    scrollController = ScrollController()
      ..addListener(() {
        if (isLoading == false &&
            scrollController.position.pixels >= scrollController.position.maxScrollExtent) {
          setState(() {
            isLoading = true;
          });
          loadMoreData();
        }
      });
    initData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      controller: scrollController,
      slivers: [
        SliverList(
            delegate: SliverChildBuilderDelegate((context, index) {
          var row = pageList[index];
          return Center(
            child: Container(
              width: 345,
              height: 70,
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    bottomLeft:
                        index + 1 < pageList.length ? const Radius.circular(10) : Radius.zero,
                    bottomRight:
                        index + 1 < pageList.length ? const Radius.circular(10) : Radius.zero,
                  )),
              child: Row(
                children: [
                  Expanded(
                      child: Container(
                    padding: EdgeInsets.only(left: 15.w),
                    child: Column(
                      children: [
                        Expanded(
                            child: Align(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            row.name,
                            style: StylesUtils.customTextStyle(
                                fontSize: 15.sp, color: ColorsUtils.color3333),
                          ),
                        )),
                        Expanded(
                            child: Align(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            row.time,
                            style: StylesUtils.customTextStyle(
                                fontSize: 12.sp, color: ColorsUtils.color9999),
                          ),
                        ))
                      ],
                    ),
                  )),
                  Center(
                    child: Text(
                      '-${NumberFormat('#,###').format(row.count)}',
                      style: StylesUtils.customTextStyle(
                          fontSize: 16.sp, color: ColorsUtils.colorFf00),
                    ),
                  )
                ],
              ),
            ),
          );
        }, childCount: pageList.length)),
        if (hasNext == false) noBottom() else if (isLoading == true) renderBottom()
      ],
    );
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  SliverToBoxAdapter noBottom() {
    return SliverToBoxAdapter(
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 15),
        alignment: Alignment.center,
        child: const Text(
          '已经到底',
          style: TextStyle(
            fontSize: 15,
            color: Color(0xFF333333),
          ),
        ),
      ),
    );
  }

  SliverToBoxAdapter renderBottom() {
    if (isLoading == true) {
      return SliverToBoxAdapter(
          child: Container(
        padding: const EdgeInsets.symmetric(vertical: 15),
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '努力加载中...',
              style: TextStyle(
                fontSize: 15,
                color: Color(0xFF333333),
              ),
            ),
            Padding(padding: EdgeInsets.only(left: 10)),
            SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(strokeWidth: 3),
            ),
          ],
        ),
      ));
    }
    return SliverToBoxAdapter(
        child: Container(
      padding: const EdgeInsets.symmetric(vertical: 15),
      alignment: Alignment.center,
      child: const Text(
        '上拉加载更多',
        style: TextStyle(
          fontSize: 15,
          color: Color(0xFF333333),
        ),
      ),
    ));
  }

  void initData() {
    var r = Random.secure();
    for (var i = 0; i < 10; i++) {
      pageList.add(GoldCoinModel(
          count: r.nextInt(100000) + r.nextInt(987) + 100000,
          name: '支付抵扣金币-门票',
          time: '2023-11-24 18:51',
          type: 2));
    }
  }

  Future<void> loadMoreData() {
    return Future.delayed(const Duration(seconds: 1), () {
      setState(() {
        if (total > pageList.length) {
          hasNext = true;
          isLoading = false;
          initData();
          return;
        }
        hasNext = false;
        isLoading = false;
      });
    });
  }
}
